#!/usr/bin/env python

from cookie_manager import CookieManager
from session import Session
import sys
import inspect

class logging_class ():
	LOG_DEBUG = 1
	LOG_INFO  = 2
	LOG_WARN  = 3
	LOG_ERROR = 4
	LOG_CRITICAL = 5

	def __init__ ( self ):
		self.full = 1
		self.level = self.LOG_ERROR

	def debug ( self, txt ):
		self._txt ( self.LOG_DEBUG, txt )

	def info ( self, txt ):
		self._txt ( self.LOG_INFO, txt )

	def warn ( self, txt ):
		self._txt ( self.LOG_WARN, txt )

	def error ( self, txt ):
		self._txt ( self.LOG_ERROR, txt )

	def critical ( self, txt ):
		self._txt ( self.LOG_CRITICAL, txt )

	def _txt ( self, lvl, txt ):
		if self.level > lvl: return
	
		if self.full:
			stk = inspect.stack () [ 2 ]
			fname = "[%s, %s, %s]: " % ( stk [ 1 ], stk [ 2 ], stk [ 3 ] )
		else:
			fname = ""

		sys.stderr.write ( "%s%s\n" % ( fname,  txt ) )

	def getLogger ( self, *args, **kargs ):
		return self

logging = logging_class ()

class PyHP ( object ):
	def __init__ ( self ):
		self._headers = {}

		self.get = {}
		self.post = {}

		self.log = logging

		self.session = Session ( self )

		self._debug_fname = ""

	def set_debug ( self, fname ):
		self._debug_fname = fname

	def debug ( self, txt ):
		if not self._debug_fname: return
	
		try:
			file ( self._debug_fname, "a" ).write ( txt )
		except:
			pass

	def init ( self, environ ):
		self.env = environ

		self.cookies = CookieManager ( self )
		self.uploads = {}
		self._headers = {}
		self.session.init ()

		self.cookies.read ( environ.get ( "HTTP_COOKIE", "" ) )
		self.set_http_code ( 200 )

	def set_header ( self, name, value ):
		self._headers [ name ] = str ( value )


	def redirect ( self, url ):
		self.set_http_code ( 301 )
		self.set_header ( 'Location', url )

	def set_http_code ( self, code ):
		codes = { 	200 : "200 OK",
				301 : "301 Moved Permanently",
				404 : "404 Not Found" }

		self.return_code = codes.get ( code, "%s - Unknown code" % code )

	def page_not_found ( self ):
		self.set_http_code ( 404 )
		self.set_header ( "Content-Type", "text/plain" )
		print ( "404 Page not found" )


	def _guess_mimetype ( self, path_name = '' ):
		import mimetypes

		return mimetypes.guess_type ( path_name )

	def send_file ( self, path, file_name = '', mime = '', bindata = '', disposition = "attachment" ):
		import os

		try:
			data = open ( path, "rb" ).read ()
		except:
			if bindata: 
				data = bindata	
			else:
				self.set_http_code ( 404 )
				return

		if not file_name: file_name = os.path.basename ( path )
		if not mime: mime = self._guess_mimetype ( path ) [ 0 ]
		if not mime: mime = 'application/octet-stream'

		self.set_header (  'Content-Type', mime )
		self.set_header (  'Content-Length', str ( len ( data ) ) )
		self.set_header (  'Content-Transfer-Encoding', "binary" )
		if disposition == 'attachment':
			self.set_header (  'Content-Disposition', 'attachment; filename="%s"' % file_name )
		else:
			self.set_header (  'Content-Disposition', 'inline' )
		
		print data
		

	def get_headers ( self ):
		"""
		Prende tutti gli headers di output
		"""

		if 'Content-Type' not in self._headers:
			self._headers [ 'Content-Type' ] = 'text/html; charset="utf-8"'

		headers = []
		for k, v in self._headers.iteritems ():
			headers.append ( ( k, v ) )

		if self.env [ 'pyhp_target_type' ] == 'pyhp':
			for cook in self.cookies.dump ():
				headers.append ( ( 'Set-Cookie', cook ) )

		return headers
